#include "serial_port.h"
#include "data_codec.h"
#include <iostream>

void data_received_callback(const std::vector<uint8_t> &data, DataCodec &codec) {
    std::vector<std::unique_ptr<pkt_t>> decoded_packets = codec.decode(data);
    for (const auto &packet : decoded_packets) {
        // 处理解码后的数据包
        std::cout << "Received Packet with Sequence: " << packet->seq << std::endl;
    }
}

void serial_receiver_example(const std::string &port_name, int baud_rate, bool ctsrts) {
    try {
        serial_port sp(port_name, baud_rate, ctsrts);
        DataCodec codec;

        sp.set_data_callback([&codec](const std::vector<uint8_t> &data) {
            data_received_callback(data, codec);
        });

        sp.open_port();

        std::this_thread::sleep_for(std::chrono::seconds(300));  // 模拟接收数据 30 秒

        sp.close_port();
    } catch (const std::exception &e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <port_name> [baud_rate] [ctsrts]" << std::endl;
        return 1;
    }

    std::string port_name = argv[1];
    int baud_rate = B115200;
    bool ctsrts = false;

    if (argc >= 3) {
        int baud = std::stoi(argv[2]);
        switch (baud) {
            case 9600:
                baud_rate = B9600;
                break;
            case 19200:
                baud_rate = B19200;
                break;
            case 38400:
                baud_rate = B38400;
                break;
            case 57600:
                baud_rate = B57600;
                break;
            case 115200:
                baud_rate = B115200;
                break;
            case 1000000:
                baud_rate = B1000000;
                break;
            default:
                std::cerr << "Unsupported baud rate. Using default 115200." << std::endl;
                break;
        }
    }

    if (argc >= 4) {
        ctsrts = std::stoi(argv[3]) != 0;
    }

    serial_receiver_example(port_name, baud_rate, ctsrts);

    return 0;
}
